package com.qlh.composewidget.useage

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.widget.ImageView
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.fragment.app.Fragment
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.UriUtils
import com.bumptech.glide.Glide
import com.feeyo.groundservice.composewidget.util.intervalClick
import com.feeyo.groundservice.composewidget.util.toComposeColor
import com.feeyo.groundservice.composewidget.view.util.VerticalSpace
import com.feeyo.groundservice.easyphotoplus.basic.PictureSelector
import com.feeyo.groundservice.easyphotoplus.config.PictureConfig
import com.feeyo.groundservice.easyphotoplus.config.SelectMimeType
import com.feeyo.groundservice.easyphotoplus.entity.LocalMedia
import com.feeyo.groundservice.easyphotoplus.interfaces.OnCallbackListener
import com.feeyo.groundservice.easyphotoplus.interfaces.OnCameraInterceptListener
import com.feeyo.groundservice.easyphotoplus.interfaces.OnRecordAudioInterceptListener
import com.feeyo.groundservice.easyphotoplus.interfaces.OnResultCallbackListener
import com.feeyo.groundservice.easyphotoplus.use.EasyPhotoPlusUtil
import com.feeyo.groundservice.easyphotoplus.use.RecorderVoiceUtil
import com.luck.lib.camerax.CameraImageEngine
import com.luck.lib.camerax.SimpleCameraX
import com.qlh.composewidget.R


/**
 *作者：70893 on 2025-04-04
 *描述：测试  PictureSelector 3.0
 */
class TestPictureSelector : AppCompatActivity() {

    private val TAG = "TestPictureSelector"
    private val TAG_DESCRIPTION_VIEW = "TAG_DESCRIPTION_VIEW"

    private val launcher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode === RESULT_OK) {
                val data = result.data?.data
                Log.e(TAG, "onResult: ${data?.pathSegments}")
                val path = UriUtils.uri2File(data)
                Log.e(TAG, "onResult: ${path}")
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        initView()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                val data = PictureSelector.obtainSelectorList(data)
                Log.e(TAG, "onActivityResult1：${GsonUtils.toJson(data)}")
            } else if (requestCode == PictureConfig.REQUEST_CAMERA) {
                val data = PictureSelector.obtainSelectorList(data)
                Log.e(TAG, "onActivityResult2：${GsonUtils.toJson(data)}")
            } else if (requestCode == 100) {
                data?.data?.let {
                    Log.e(TAG, "onActivityResult3：${it.path}")
                }
            }
        } else if (resultCode == RESULT_CANCELED) {
            Log.e(TAG, "onActivityResult：cancel")
        }
    }


    private fun initView() {
        setContent {

            Column {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {

                    Box(
                        contentAlignment = Alignment.Center,
                        modifier = Modifier
                            .background(
                                color = R.color.blue_4796F4.toComposeColor(),
                                shape = RoundedCornerShape(5.dp),
                            )
                            .padding(5.dp).intervalClick { openAlbum(SelectMimeType.ofAll()) }
                    ) {
                        Text(
                            text = "相册+ALL"//拍照 视频，录音（待开发）
                        )
                    }

                    Box(
                        contentAlignment = Alignment.Center,
                        modifier = Modifier
                            .background(
                                color = R.color.blue_4796F4.toComposeColor(),
                                shape = RoundedCornerShape(5.dp),
                            )
                            .padding(5.dp).intervalClick { openAlbum(SelectMimeType.ofImage()) }
                    ) {
                        Text(
                            text = "相册+拍照"
                        )
                    }

                    Box(
                        contentAlignment = Alignment.Center,
                        modifier = Modifier
                            .background(
                                color = R.color.blue_4796F4.toComposeColor(),
                                shape = RoundedCornerShape(5.dp),
                            )
                            .padding(5.dp).intervalClick { openAlbum(SelectMimeType.ofVideo()) }
                    ) {
                        Text(
                            text = "相册+视频"
                        )
                    }

                    Box(
                        contentAlignment = Alignment.Center,
                        modifier = Modifier
                            .background(
                                color = R.color.blue_4796F4.toComposeColor(),
                                shape = RoundedCornerShape(5.dp),
                            )
                            .padding(5.dp).intervalClick { openAlbum(SelectMimeType.ofAudio()) }
                    ) {
                        Text(
                            text = "音频+录音"
                        )
                    }
                }
                VerticalSpace(10.dp)
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Box(
                        contentAlignment = Alignment.Center,
                        modifier = Modifier
                            .background(
                                color = R.color.blue_4796F4.toComposeColor(),
                                shape = RoundedCornerShape(5.dp),
                            )
                            .padding(5.dp).intervalClick { openCamera(SelectMimeType.ofImage()) }
                    ) {
                        Text(
                            text = "拍照"
                        )
                    }

                    Box(
                        contentAlignment = Alignment.Center,
                        modifier = Modifier
                            .background(
                                color = R.color.blue_4796F4.toComposeColor(),
                                shape = RoundedCornerShape(5.dp),
                            )
                            .padding(5.dp).intervalClick { openCamera(SelectMimeType.ofVideo()) }
                    ) {
                        Text(
                            text = "拍视频"
                        )
                    }

                    Box(
                        contentAlignment = Alignment.Center,
                        modifier = Modifier
                            .background(
                                color = R.color.blue_4796F4.toComposeColor(),
                                shape = RoundedCornerShape(5.dp),
                            )
                            .padding(5.dp).intervalClick { openCamera(SelectMimeType.ofAudio()) }
                    ) {
                        Text(
                            text = "录音"
                        )
                    }
                }

                VerticalSpace(10.dp)

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Box(
                        contentAlignment = Alignment.Center,
                        modifier = Modifier
                            .background(
                                color = R.color.blue_4796F4.toComposeColor(),
                                shape = RoundedCornerShape(5.dp),
                            )
                            .padding(5.dp)
                            .intervalClick { openCamera(SelectMimeType.ofImage(), true) }
                    ) {
                        Text(
                            text = "自定义拍照"
                        )
                    }

                    Box(
                        contentAlignment = Alignment.Center,
                        modifier = Modifier
                            .background(
                                color = R.color.blue_4796F4.toComposeColor(),
                                shape = RoundedCornerShape(5.dp),
                            )
                            .padding(5.dp)
                            .intervalClick { openCamera(SelectMimeType.ofVideo(), true) }
                    ) {
                        Text(
                            text = "自定义录视频"
                        )
                    }

                    Box(
                        contentAlignment = Alignment.Center,
                        modifier = Modifier
                            .background(
                                color = R.color.blue_4796F4.toComposeColor(),
                                shape = RoundedCornerShape(5.dp),
                            )
                            .padding(5.dp)
                            .intervalClick {
                                EasyPhotoPlusUtil.openFileManager(launcher)
                            }
                    ) {
                        Text(
                            text = "打开文件"
                        )
                    }
                }

                VerticalSpace(10.dp)
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Box(
                        contentAlignment = Alignment.Center,
                        modifier = Modifier
                            .background(
                                color = R.color.blue_4796F4.toComposeColor(),
                                shape = RoundedCornerShape(5.dp),
                            )
                            .padding(5.dp)
                            .intervalClick {
                                RecorderVoiceUtil.startRecord(this@TestPictureSelector, object :
                                    OnCallbackListener<String> {
                                    override fun onCall(data: String?) {

                                    }
                                })
                            }
                    ) {
                        Text(
                            text = "录音开始"
                        )
                    }


                    Box(
                        contentAlignment = Alignment.Center,
                        modifier = Modifier
                            .background(
                                color = R.color.blue_4796F4.toComposeColor(),
                                shape = RoundedCornerShape(5.dp),
                            )
                            .padding(5.dp)
                            .intervalClick {
                                RecorderVoiceUtil.stopRecord()
                            }
                    ) {
                        Text(
                            text = "录音结束"
                        )
                    }
                }
            }
        }
    }


    //相册+拍照 视频 录音
    private fun openAlbum(type: Int) {

        EasyPhotoPlusUtil.openAlbum(
            this,
            type,
            true,
            true,
            false,
            false,
            5,
            object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: ArrayList<LocalMedia>) {
                    Log.e(TAG, "onResult: ${GsonUtils.toJson(result)}")
                }

                override fun onCancel() {

                }
            }
        )


//        PictureSelector.create(this)
//            .openGallery(type)
//            .setSelectorUIStyle(getDefaultUIStyle(this))
//            .setImageEngine(GlideEngine1.createGlideEngine())
//            .setMaxSelectNum(5)
//            .setRecordAudioInterceptListener(getRecordAudioListener)
//            .isDisplayCamera(true)//是否显示拍摄按钮
//            .isDisplayTimeAxis(true)
//            .isGif(true)
//            .setCompressEngine(ImageFileCompressEngine())
//            .setCropEngine(ImageFileCropEngine())
//            .forResult(object : OnResultCallbackListener<LocalMedia> {
//                override fun onResult(result: ArrayList<LocalMedia>) {
//                    Log.e(TAG, "onResult: ${GsonUtils.toJson(result)}")
//                }
//
//                override fun onCancel() {
//
//                }
//            })
    }

    //拍照 视频 录音 直接拉起
    private fun openCamera(type: Int, isCustom: Boolean = false) {
        PictureSelector.create(this)
            .openCamera(type)
            //可以自定义保存路径
            .setCameraInterceptListener(if (isCustom) getCustomCameraListener else null)
            .setRecordVideoMaxSecond(10)
            //.isCameraForegroundService(true)
            .setRecordVideoMinSecond(10)
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: ArrayList<LocalMedia>?) {
                    Log.e(TAG, "onResult: ${GsonUtils.toJson(result)}")
                }

                override fun onCancel() {

                }
            })
    }


    private val getRecordAudioListener = object : OnRecordAudioInterceptListener {

        override fun onRecordAudio(fragment: Fragment, requestCode: Int) {
            startRecordSoundAction(fragment, requestCode)
        }
    }

    private val getCustomCameraListener = object : OnCameraInterceptListener {
        override fun openCamera(fragment: Fragment, cameraMode: Int, requestCode: Int) {

            val camera: SimpleCameraX = SimpleCameraX.of()
            camera.isAutoRotation(true)
            camera.setCameraMode(cameraMode)
            camera.setVideoFrameRate(25)
            camera.setVideoBitRate(3 * 1024 * 1024)
            camera.isDisplayRecordChangeTime(true)
            camera.isManualFocusCameraPreview(true)

            camera.setImageEngine(object : CameraImageEngine {
                override fun loadImage(context: Context, url: String?, imageView: ImageView) {
                    Glide.with(context).load(url).into(imageView)
                }
            })
            camera.start(fragment.requireActivity(), fragment, requestCode)
        }
    }


    /**
     * 启动录音意图
     *
     * @param fragment
     * @param requestCode
     */
    private fun startRecordSoundAction(fragment: Fragment, requestCode: Int) {
        val recordAudioIntent = Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION)
        if (recordAudioIntent.resolveActivity(fragment.requireActivity().packageManager) != null) {
            fragment.startActivityForResult(recordAudioIntent, requestCode)
        } else {

        }
    }
}